package com.zijing2333.adaptivescheduling.SwitcherManager.server;

import android.util.Log;

import com.zijing2333.adaptivescheduling.ChannelManager;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class SocketServer implements Runnable{
    //TAG标记
    static final String TAG = "fun_SocketServer";
    //服务器端切换服务的端口号
    //服务器端切换服务的端口号
    private final int mPort;
    //标识
    private boolean mIsRunning;
    //与客户端通信的socket

    //监听端口的ServerSocket
    private ServerSocket mServerSocket;
    //服务器端的回调
    private ServerCallback mCallback;
    //输出流


    ////表示服务器端可以同时接收多个客户端的连接
    private final List<ServerConnectClientThread> mClient = new ArrayList<>();//表示服务器端可以同时接收多个客户端的连接

    public static SocketServer launch(int Port,ServerCallback serverCallback){
        SocketServer socketServer = new SocketServer(Port, serverCallback);
        new Thread(socketServer).start();
        return socketServer;
    }

    public SocketServer(int Port,ServerCallback serverCallback) {
        this.mPort = Port;
        this.mCallback =serverCallback;
    }


    /**
     * 关闭服务
     */
    public void stopServer() {
        stopRunning();
        try {
            if (mServerSocket != null) {
                mServerSocket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (ServerConnectClientThread serverConnectClientThread:mClient){
            serverConnectClientThread.close();
        }
    }



    /**
     * 发送到客户端2，这里不再是群发了
     * @param data
     */
    public void writeString(String JsServiceId,String type,String data){
//        for (ServerConnectClientThread serverConnectClientThread: mClient){
//            serverConnectClientThread.writeString(JsServiceId,type,data);
////            mCallback.otherMsg("toClient: "+data);
//            Log.d(TAG, "toClient: "+data);
//        }
        ServerConnectClientThread serverConnectClientThread = ChannelManager.getInstance().getServerConnectClientThreadFromMap(JsServiceId);
        Log.d(TAG, "writeString:==========serverConnectClientThread不为空 ");
        serverConnectClientThread.writeString(JsServiceId,type,data);
    }

    @Override
    public void run() {
        setRunning(true);
        try {
            mServerSocket = new ServerSocket(mPort);
            Log.d(TAG, "run:服务端socket监听开启 ");
            //这里ServerSocket是一直在监听该端口的，当和某个客户端连接后，会继续监听，因此while循环
            while (mIsRunning) {
                Socket socket = mServerSocket.accept();
                if (socket != null){
                    //toString()方法返回格式为"主机名/IP地址"的字符串，例如"www.example.com/93.184.216.34"；而getHostAddress()方法只返回IP地址部分，即“93.184.216.34”，
                    String clientIp = socket.getInetAddress().getHostAddress();
                    Log.d(TAG, "服务端socket成功建立,"+clientIp+"客户端申请连接");
                    //创建一个线程，和客户端保持联系，该线程需要持有socket。（将建立的socket放入一个线程去管理）  这个线程主要接收客户端传来的数据，服务端这边进行解析，回显
                    ServerConnectClientThread serverConnetClientThread = new ServerConnectClientThread(socket, mCallback);
                    ChannelManager.getInstance().addServerConnectClientThreadMap(clientIp,serverConnetClientThread);
                    mClient.add(serverConnetClientThread); //放入一个Lsit列表中，方便接收多个客户端的请求
                    new Thread(serverConnetClientThread).start();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    private void setRunning(boolean running) {
        mIsRunning = running;
    }
    public void stopRunning() {
        setRunning(false);
    }
}
